﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using HalconDotNet;
using System.IO;

namespace AssemblyCYG
{
    public partial class CalibForm : Form
    {
        HalconAlgorithm halconAlgorithm = new HalconAlgorithm();
        ConcurrentQueue<Bitmap> aloneCalibQueue = new ConcurrentQueue<Bitmap>();        //相机独立标定
        ConcurrentQueue<Bitmap> relateCalibDCamQueue = new ConcurrentQueue<Bitmap>();       //关联标定下相机
        ConcurrentQueue<Bitmap> relateCalibUCamQueue = new ConcurrentQueue<Bitmap>();       //关联标定下相机
        Thread aloneCalibThread = null;
        Thread reCalibDownCamThread = null;
        Thread reCalibUpCamThread = null;
        Thread requestPhotoThread = null;
        bool getDownCamStandPos { get; set; }   //是否实时处理下相机图像
        bool getUpCamStandPos { get; set; }
        bool threadBusy = false;
        bool photoSignal { get; set; }              //接收到的相机拍照信号
        bool receiPosSignal { get; set; }           //收到plc位置信号
        double curPLCPos_X;                   //相机独立标定时PLC位置信号
        double curPLCPos_Y;                   //相机独立标定时PLC位置信号
        double curPLCPos_Phi;                 //相机独立标定时PLC位置信号

        //Point[] curPixelPos;
        double[] curPixelPos_X;               //独立标定时的当前像素位置
        double[] curPixelPos_Y;
        double[] curPixelAngle;               //独立标定时的当前像素角度
        int calibCurNum = 0;                  //相机独立标定当前走位索引
        int calibTotalNum = 0;                //相机独立标定走位总次数，下相机七步，上相机三步

        int curOffCalibIndex;     //离线标定索引
        CalibModel calibModel;
        public enum CalibModel
        {
            七步,
            三步,
        }
        public CalibForm()
        {
            InitializeComponent();
            InatialControls();      //初始化控件
            LoadCalPara();          //初始化标定参数           
            ShareData.MvsCameral.captureImage += MvsCameral_captureImage;   //委托采集图像
            InitialCameral();       //初始化相机
            //InitialTcpSocket();     //初始化modbus tcp通讯           
            //ShareData.tcpClient.receiveInfoHandler += tcpClient_receiveInfoHandler;    //委托接收信息            
            threadBusy = true;
            photoSignal = false;
            receiPosSignal = false;
            getDownCamStandPos = false;
            getUpCamStandPos = false;
            StartThread();          //开启线程
        }
        private void LoadCalPara()
        {
            try
            {
                this.tB_downCampixelSize_X.Text = ShareData.downCamPixSize_X.ToString();
                this.tB_downCampixelSize_Y.Text = ShareData.downCamPixSize_Y.ToString();
                this.tB_downCampixelSize_Phi.Text = ShareData.downCamPixSize_Phi.ToString();
                this.tB_upCampixelSize_Y.Text = ShareData.upCamPixSize1_Y.ToString();         //上相机只有Y方向标定

                this.tB_dCamStandPos_X.Text = ShareData.dowCamStandPos_X.ToString();
                this.tB_dCamStandPos_Y.Text = ShareData.dowCamStandPos_Y.ToString();
                this.tB_dCamStandPos_Phi.Text = ShareData.dowCamStandPos_Phi.ToString();

                this.tB_uCamStandPos_X.Text = ShareData.upCamStandPos1_X.ToString();
                this.tB_uCamStandPos_Y.Text = ShareData.upCamStandPos1_Y.ToString();
                this.tB_uCamStandPos_Phi.Text = ShareData.upCamStandPos1_Phi.ToString();

                this.tB_calibOutCircleRadius.Text = ProjectInfo.Parameter.calibOutCircleRadius.ToString();
                this.tB_calibSeekStartPhi.Text = ProjectInfo.Parameter.calibSeekCornerStartPhi.ToString();
                this.tB_calibSeekEndPhi.Text = ProjectInfo.Parameter.calibSeekCornerEndPhi.ToString();

                this.tB_calibUpOutCircleRadius.Text = ProjectInfo.Parameter.calibUpOutCircleRadius.ToString();
                this.tB_calibUpSeekStartPhi.Text = ProjectInfo.Parameter.calibUpSeekCornerStartPhi.ToString();
                this.tB_calibUpSeekEndPhi.Text = ProjectInfo.Parameter.calibUpSeekCornerEndPhi.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void MvsCameral_captureImage(int cameralIndex, Bitmap image)
        {
            if (ProjectInfo.Parameter.downCamIndex == cameralIndex)
            {
                //下相机                
                if (getDownCamStandPos)                  //必须处于相机取图模式
                {
                    getDownCamStandPos = false;
                    if (relateCalibDCamQueue.IsEmpty)
                        relateCalibDCamQueue.Enqueue(image);
                }
                else if (photoSignal && calibTotalNum == 7)   //下相机七步标定
                {
                    photoSignal = false;
                    if (aloneCalibQueue.IsEmpty)        //防止队列积累内存
                        aloneCalibQueue.Enqueue(image);
                }
                else
                    this.pictureBox_downCam.Image = image;
            }
            else if (ProjectInfo.Parameter.upCamIndex == cameralIndex)
            {
                //上相机      
                if (getUpCamStandPos)
                {
                    getUpCamStandPos = false;
                    //上相机
                    if (relateCalibUCamQueue.IsEmpty)
                        relateCalibUCamQueue.Enqueue(image);
                }
                else if (photoSignal && calibTotalNum == 3)      //上相机三步标定
                {
                    photoSignal = false;
                    if (aloneCalibQueue.IsEmpty)   //防止队列积累内存
                        aloneCalibQueue.Enqueue(image);
                }
                else
                    this.pictureBox_upCam.Image = image;
            }
        }
        private void StartThread()
        {
            this.aloneCalibThread = new Thread(StartAloneCalib);
            this.aloneCalibThread.IsBackground = true;
            this.aloneCalibThread.Start();
            this.reCalibDownCamThread = new Thread(StartRelateCalibDownCam);
            this.reCalibDownCamThread.IsBackground = true;
            this.reCalibDownCamThread.Start();
            this.reCalibUpCamThread = new Thread(StartRelateCalibUpCam);
            this.reCalibUpCamThread.IsBackground = true;
            this.reCalibUpCamThread.Start();
        }
        private bool InitialCameral()
        {
            List<string> deviceInfo = new List<string>();
            if (ShareData.MvsCameral.CameralDeviceListAcq(out deviceInfo))                      //初始化设备，可以重复初始化设备,可以预防工程建好后重新加入相机
            {
                if (deviceInfo.Count > 0)
                {
                    for (int i = 0; i < deviceInfo.Count; i++)
                    {
                        if (!ShareData.MvsCameral.OpenDevice(i))               //打开设备
                        {
                            MessageBox.Show("打开相机失败！");
                            return false;
                        }
                        if (ShareData.MvsCameral.StartHKCamGrab(i) != 0)      //开始采集
                        {
                            MessageBox.Show("打开相机失败");
                            return false;
                        }
                        ShareData.MvsCameral.SetContinueGrab(i);             //设置为连续采集模式
                        ShareData.cameralOpenList.Add(i);
                    }
                    //if (ProjectInfo.Parameter.downCamIndex == ProjectInfo.Parameter.upCamIndex)
                    //{
                    //    MessageBox.Show("检测到上下相机的索引，请先设置相机参数！");
                    //    return false;
                    //}
                    if (ProjectInfo.Parameter.downCamIndex < 0 || ProjectInfo.Parameter.downCamIndex > deviceInfo.Count - 1)
                    {
                        MessageBox.Show("请先设置下相机");
                        return false;
                    }
                    if (ProjectInfo.Parameter.upCamIndex < 0 || ProjectInfo.Parameter.upCamIndex > deviceInfo.Count - 1)
                    {
                        MessageBox.Show("请先设置上相机");
                        return false;
                    }
                }
                else
                {
                    MessageBox.Show("查找到相机的数量为0");
                    return false;
                }
            }
            else
            {
                MessageBox.Show("初始化相机失败！");
                return false;
            }
            return true;
        }
        private void InatialControls()
        {
            this.cB_selCalCamera.SelectedIndex = 0;
            InitialHalconWindow(this.hWindow_rotate1.HalconWindow);
            InitialHalconWindow(this.hWindow_rotate2.HalconWindow);
            InitialHalconWindow(this.hWindow_center.HalconWindow);
            InitialHalconWindow(this.hWindow_up.HalconWindow);
            InitialHalconWindow(this.hWindow_down.HalconWindow);
            InitialHalconWindow(this.hWindow_left.HalconWindow);
            InitialHalconWindow(this.hWindow_right.HalconWindow);
            InitialHalconWindow(this.hWindow_reDownCam.HalconWindow);
            InitialHalconWindow(this.hWindow_reUpCam.HalconWindow);
            this.cB_getImageType.SelectedIndex = 0;
        }
        private void InitialHalconWindow(HTuple windowHandle)
        {
            HOperatorSet.SetDraw(windowHandle, "margin");
            HOperatorSet.SetLineWidth(windowHandle, 2);
            HOperatorSet.SetColor(windowHandle, "blue");
        }
        private void StartRelateCalibDownCam()      //开启关联下相机标定
        {
            while (threadBusy)
            {
                Bitmap inputBmp = null;
                if (!relateCalibDCamQueue.IsEmpty)
                {
                    bool nflag = relateCalibDCamQueue.TryDequeue(out inputBmp);
                    if (!nflag || inputBmp == null) continue;
                    HObject ho_Image = null;
                    HOperatorSet.GenEmptyObj(out ho_Image);
                    ho_Image.Dispose();
                    ho_Image = halconAlgorithm.Bitmap2HObject(inputBmp);  //用于实时显示图像
                    HTuple hv_ImageWidth, hv_ImageHeight;
                    HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
                    ho_AdaptiveImage(hWindow_reDownCam, hv_ImageWidth, hv_ImageHeight);
                    hWindow_reDownCam.HalconWindow.ClearWindow();
                    HOperatorSet.DispObj(ho_Image, hWindow_reDownCam.HalconWindow);
                    //后续可以增加走位时的处理
                    double circle_X = 0;
                    double circle_Y = 0;
                    double angle = 0;
                    HObject ho_fitCircleContour = null;
                    HObject ho_fitLine1Contour = null;
                    // HObject ho_fitLine2Contour = null;
                    // HObject ho_fitAngleLine = null;
                    if (ProcessDownCamImage(ho_Image, out ho_fitCircleContour, out ho_fitLine1Contour, out circle_X, out circle_Y, out angle))
                    {
                        HOperatorSet.DispObj(ho_fitCircleContour, hWindow_reDownCam.HalconWindow);
                        HOperatorSet.DispObj(ho_fitLine1Contour, hWindow_reDownCam.HalconWindow);
                       // HOperatorSet.DispObj(ho_fitLine2Contour, hWindow_reDownCam.HalconWindow);
                       // HOperatorSet.DispObj(ho_fitAngleLine, hWindow_reDownCam.HalconWindow);
                        this.Invoke(new Action(() =>
                        {
                            this.tB_dCamStandPos_X.Text = circle_X.ToString("f3");
                            this.tB_dCamStandPos_Y.Text = circle_Y.ToString("f3");
                            this.tB_dCamStandPos_Phi.Text = angle.ToString("f3");
                        }));
                    }
                    ho_fitCircleContour.Dispose();
                    ho_fitLine1Contour.Dispose();
                    //  ho_fitLine2Contour.Dispose();
                    // ho_fitAngleLine.Dispose();
                }
                Thread.Sleep(2);
            }
        }
        private void StartRelateCalibUpCam()      //开启关联上相机标定
        {
            while (threadBusy)
            {
                Bitmap inputBmp = null;
                if (!relateCalibUCamQueue.IsEmpty)
                {
                    bool nflag = relateCalibUCamQueue.TryDequeue(out inputBmp);
                    if (!nflag || inputBmp == null) continue;
                    HObject ho_Image = null;
                    HOperatorSet.GenEmptyObj(out ho_Image);
                    ho_Image.Dispose();
                    ho_Image = halconAlgorithm.Bitmap2HObject(inputBmp);  //用于实时显示图像
                    HTuple hv_ImageWidth, hv_ImageHeight;
                    HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
                    ho_AdaptiveImage(hWindow_reUpCam, hv_ImageWidth, hv_ImageHeight);
                    hWindow_reUpCam.HalconWindow.ClearWindow();
                    HOperatorSet.DispObj(ho_Image, hWindow_reUpCam.HalconWindow);
                    //后续可以增加走位时的处理
                    double circle_X = 0;
                    double circle_Y = 0;
                    double angle = 0;
                    HObject ho_fitCircleContour = null;
                    HObject ho_fitLine1Contour = null;
                    HObject ho_fitLine2Contour = null;
                    HObject ho_fitAngleLine = null;
                    if (ProcessUpCamImage(ho_Image, out ho_fitCircleContour, out ho_fitLine1Contour, out ho_fitLine2Contour, out ho_fitAngleLine, out circle_X, out circle_Y, out angle))
                    {
                        HOperatorSet.DispObj(ho_fitCircleContour, hWindow_reUpCam.HalconWindow);
                        HOperatorSet.DispObj(ho_fitLine1Contour, hWindow_reUpCam.HalconWindow);
                        HOperatorSet.DispObj(ho_fitLine2Contour, hWindow_reUpCam.HalconWindow);
                        HOperatorSet.DispObj(ho_fitAngleLine, hWindow_reUpCam.HalconWindow);
                        this.Invoke(new Action(() =>
                        {
                            this.tB_uCamStandPos_X.Text = circle_X.ToString("f3");
                            this.tB_uCamStandPos_Y.Text = circle_Y.ToString("f3");
                            this.tB_uCamStandPos_Phi.Text = angle.ToString("f3");
                        }));
                    }
                    ho_fitCircleContour.Dispose();
                    ho_fitLine1Contour.Dispose();
                    ho_fitLine2Contour.Dispose();
                    ho_fitAngleLine.Dispose();
                }
                Thread.Sleep(2);
            }
        }
        private void StartAloneCalib()     //开启独立标定
        {
            while (threadBusy)
            {
                Bitmap inputBmp = null;
                if (!aloneCalibQueue.IsEmpty)
                {
                    bool nflag = aloneCalibQueue.TryDequeue(out inputBmp);
                    if (!nflag || inputBmp == null) continue;
                    //后续可以增加走位时的处理
                    HObject ho_Image = null;
                    HOperatorSet.GenEmptyObj(out ho_Image);
                    ho_Image.Dispose();
                    //HOperatorSet.ReadImage(out ho_Image, "F:\\procedure\\运泰利P70项目\\P70_1\\b.png");    //加载图像
                    ho_Image = halconAlgorithm.Bitmap2HObject(inputBmp);  //用于实时显示图像
                    HTuple hv_ImageWidth, hv_ImageHeight;
                    HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
                    //HOperatorSet.WriteImage(ho_Image, "bmp", 0, "angle1.bmp");
                    //处理图像..............
                    //获取当前位置的像素坐标和角度x、y、phi，并记录下来
                    double circle_X = 0;
                    double circle_Y = 0;
                    double angle = 0;
                    HObject ho_fitCircleContour = null;
                    HObject ho_fitLine1Contour = null;
                    HObject ho_fitLine2Contour = null;
                    HObject ho_fitAngleLine = null;
                    if (calibModel == CalibModel.七步)
                    {
                        //下相机标定
                        if (!ProcessDownCamImage(ho_Image, out ho_fitCircleContour, out ho_fitLine1Contour, out circle_X, out circle_Y, out angle))
                        {
                            HOperatorSet.WriteImage(ho_Image, "bmp", 0, "errorAloneDown.bmp");
                            continue;
                        }
                    }
                    else if (calibModel == CalibModel.三步)
                    {
                        //上相机标定
                        if (!ProcessUpCamImage(ho_Image, out ho_fitCircleContour, out ho_fitLine1Contour, out ho_fitLine2Contour, out ho_fitAngleLine, out circle_X, out circle_Y, out angle))
                        {
                            HOperatorSet.WriteImage(ho_Image, "bmp", 0, "errorAloneUp.bmp");
                            continue;
                        }
                    }

                    string curPixPos = string.Format("X:{0} Y:{1} Phi:{2}", circle_X.ToString("f4"), circle_Y.ToString("f4"), angle.ToString("f4"));     //求出的像素坐标待替换
                    curPixelPos_X[curOffCalibIndex - 1] = circle_X;
                    curPixelPos_Y[curOffCalibIndex - 1] = circle_Y;       //当前像素位置
                    curPixelAngle[curOffCalibIndex - 1] = angle;          //角度
                    string modelImageFold = "";
                    if (calibModel == CalibModel.七步)
                        modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "calib", "downCam");
                    else
                        modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "calib", "upCam");
                    if (!Directory.Exists(modelImageFold)) Directory.CreateDirectory(modelImageFold);
                    this.Invoke(new Action(() =>
                    {
                        switch (curOffCalibIndex)                      //显示当前图像和位置
                        {
                            case 1:
                                //中间位置   
                                ho_AdaptiveImage(this.hWindow_center, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_center.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_center.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_center.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_center.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_center.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_center.HalconWindow);
                                this.lab_curCenterPos.Text = curPixPos;
                                this.lab_curCenterPos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\center.bmp");
                                break;
                            case 2:
                                //上移一步   
                                ho_AdaptiveImage(this.hWindow_up, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_up.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_up.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_up.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_up.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_up.HalconWindow);
                                //  HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_up.HalconWindow);
                                this.lab_curUpPos.Text = curPixPos;
                                this.lab_curUpPos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\up.bmp");
                                break;
                            case 3:
                                //下移一步
                                ho_AdaptiveImage(this.hWindow_down, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_down.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_down.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_down.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_down.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_down.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_down.HalconWindow);
                                this.lab_curDownPos.Text = curPixPos;
                                this.lab_curDownPos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\down.bmp");
                                break;
                            case 4:
                                //左移一步
                                ho_AdaptiveImage(this.hWindow_left, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_left.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_left.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_left.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_left.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_left.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_left.HalconWindow);
                                this.lab_curLeftPos.Text = curPixPos;
                                this.lab_curLeftPos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\left.bmp");
                                break;
                            case 5:
                                //右移一步
                                ho_AdaptiveImage(this.hWindow_right, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_right.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_right.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_right.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_right.HalconWindow);
                                //HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_right.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_right.HalconWindow);
                                this.lab_curRightPos.Text = curPixPos;
                                this.lab_curRightPos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\right.bmp");
                                break;
                            case 6:
                                //顺时针旋转一度
                                ho_AdaptiveImage(this.hWindow_rotate1, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_rotate1.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_rotate1.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_rotate1.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_rotate1.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_rotate1.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_rotate1.HalconWindow);
                                this.lab_curRotate1Pos.Text = curPixPos;
                                this.lab_curRotate1Pos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\angle1.bmp");
                                break;
                            case 7:
                                //逆时针旋转一度
                                ho_AdaptiveImage(this.hWindow_rotate2, hv_ImageWidth, hv_ImageHeight);
                                this.hWindow_rotate2.HalconWindow.ClearWindow();
                                HOperatorSet.DispObj(ho_Image, this.hWindow_rotate2.HalconWindow);
                                HOperatorSet.DispObj(ho_fitCircleContour, this.hWindow_rotate2.HalconWindow);
                                HOperatorSet.DispObj(ho_fitLine1Contour, this.hWindow_rotate2.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitLine2Contour, this.hWindow_rotate2.HalconWindow);
                                // HOperatorSet.DispObj(ho_fitAngleLine, this.hWindow_rotate2.HalconWindow);
                                this.lab_curRotate2Pos.Text = curPixPos;
                                this.lab_curRotate2Pos.BackColor = Color.Green;
                                HOperatorSet.WriteImage(ho_Image, "bmp", 0, modelImageFold + "\\angle2.bmp");
                                break;
                        }
                    }));
                    ho_fitCircleContour.Dispose();
                    ho_fitLine1Contour.Dispose();
                    // ho_fitLine2Contour.Dispose();
                    //   ho_fitAngleLine.Dispose();
                }
                Thread.Sleep(2);
            }
        }
        //  private bool ProcessDownCamImage(HObject ho_Image, out HObject ho_fitCircleContour, out HObject ho_fitLine1Contour, out HObject ho_fitLine2Contour,
        //out HObject ho_fitAngleLine, out double circle_X, out double circle_Y, out double angle)
        private bool ProcessDownCamImage(HObject ho_Image, out HObject ho_fitCircleContour, out HObject ho_fitLine1Contour,
                out double circle_X, out double circle_Y, out double angle)
        {
            ho_fitCircleContour = null;
            ho_fitLine1Contour = null;
            // ho_fitLine2Contour = null;
            // ho_fitAngleLine = null;
            HTuple hv_ImageWidth, hv_ImageHeight = null;
            //HOperatorSet.ReadImage(out ho_Image, openFileDialog.FileName);    //加载图像
            HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
            circle_X = 0;
            circle_Y = 0;
            angle = 0;
            string bugInfo = "";
            HTuple hv_matchModel = null;
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calib");
            if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 0)   //基于形状
            {
                string shapeModelFile = modelImageFold + "\\model.shm";
                if (!File.Exists(shapeModelFile))
                {
                    MessageBox.Show("模板文件不存在，请先加载模型！");
                    return false;
                }
                HOperatorSet.ReadShapeModel(shapeModelFile, out hv_matchModel);  //加载模板
            }
            else if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 1)  //基于灰度
            {
                string nccModelFile = modelImageFold + "\\model.ncm";
                if (!File.Exists(nccModelFile))
                {
                    MessageBox.Show("模板文件不存在，请先加载模型！");
                    return false;
                }
                HOperatorSet.ReadNccModel(nccModelFile, out hv_matchModel);  //加载模板
            }
            HObject downCamROI_circle = null;
            HObject downCamROI_line1 = null;
            // HObject downCamROI_line2 = null;
            HOperatorSet.GenEmptyObj(out downCamROI_circle);
            HOperatorSet.GenEmptyObj(out downCamROI_line1);
            // HOperatorSet.GenEmptyObj(out downCamROI_line2);
            string downCircleFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calib") + "//circle.hobj";
            if (File.Exists(downCircleFile)) downCamROI_circle.ReadObject(downCircleFile);           //读取roi
            else
            {
                MessageBox.Show("下相机circleRegion为空！");
                return false;
            }
            string downLine1File = Path.Combine(System.Environment.CurrentDirectory, "region", "calib") + "//line1.hobj";
            if (File.Exists(downLine1File)) downCamROI_line1.ReadObject(downLine1File);           //读取roi
            else
            {
                MessageBox.Show("下相机line1Region为空！");
                return false;
            }
            string downLine2File = Path.Combine(System.Environment.CurrentDirectory, "region", "calib") + "//line2.hobj";
            //if (File.Exists(downLine2File)) downCamROI_line2.ReadObject(downLine2File);           //读取roi
            //else
            //{
            //    MessageBox.Show("下相机line2Region为空！");
            //    return false;
            //}
            //if (!halconAlgorithm.GetSpringPosition_match(ho_Image, hv_matchModel, ProjectInfo.Parameter.calibMatchPara, ProjectInfo.Parameter.calibFitCirclePara,
            //    ProjectInfo.Parameter.calibFitLine1Para, ProjectInfo.Parameter.calibFitLine2Para, downCamROI_circle, downCamROI_line1, downCamROI_line2, ProjectInfo.Parameter.calibOutCircleRadius / ShareData.downCamPixSize_X,
            //    ProjectInfo.Parameter.calibSeekCornerStartPhi, ProjectInfo.Parameter.calibSeekCornerEndPhi,
            //    out ho_fitCircleContour, out ho_fitLine1Contour, out ho_fitLine2Contour,
            //    out ho_fitAngleLine, out circle_X, out circle_Y, out angle, out bugInfo))

            if (!halconAlgorithm.GetCoilPosition_match(ho_Image, hv_matchModel, ProjectInfo.Parameter.calibMatchPara, ProjectInfo.Parameter.calibFitCirclePara,
                ProjectInfo.Parameter.calibFitLine1Para, downCamROI_circle, downCamROI_line1, out ho_fitCircleContour, out ho_fitLine1Contour,
                 out circle_X, out circle_Y, out angle, out bugInfo))
            {
                MessageBox.Show(bugInfo);
                return false;
            }
            if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 0)   //基于形状
            {
                HOperatorSet.ClearShapeModel(hv_matchModel);                     //清除模板
            }
            else if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 1)  //基于灰度
            {
                HOperatorSet.ClearNccModel(hv_matchModel);                   //清除模板
            }
            return true;
        }
        private bool ProcessUpCamImage(HObject ho_Image, out HObject ho_fitCircleContour, out HObject ho_fitLine1Contour, out HObject ho_fitLine2Contour,
out HObject ho_fitAngleLine, out double circle_X, out double circle_Y, out double angle)
        {
            ho_fitCircleContour = null;
            ho_fitLine1Contour = null;
            ho_fitLine2Contour = null;
            ho_fitAngleLine = null;
            HTuple hv_ImageWidth, hv_ImageHeight = null;
            //HOperatorSet.ReadImage(out ho_Image, openFileDialog.FileName);    //加载图像
            HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
            circle_X = 0;
            circle_Y = 0;
            angle = 0;
            string bugInfo = "";
            HTuple hv_matchModel = null;
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calibup");
            if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 0)   //基于形状
            {
                string shapeModelFile = modelImageFold + "\\model.shm";
                if (!File.Exists(shapeModelFile))
                {
                    MessageBox.Show("模板文件不存在，请先加载模型！");
                    return false;
                }
                HOperatorSet.ReadShapeModel(shapeModelFile, out hv_matchModel);  //加载模板
            }
            else if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 1)  //基于灰度
            {
                string nccModelFile = modelImageFold + "\\model.ncm";
                if (!File.Exists(nccModelFile))
                {
                    MessageBox.Show("模板文件不存在，请先加载模型！");
                    return false;
                }
                HOperatorSet.ReadNccModel(nccModelFile, out hv_matchModel);  //加载模板
            }
            HObject downCamROI_circle = null;
            HObject downCamROI_line1 = null;
            HObject downCamROI_line2 = null;
            HOperatorSet.GenEmptyObj(out downCamROI_circle);
            HOperatorSet.GenEmptyObj(out downCamROI_line1);
            HOperatorSet.GenEmptyObj(out downCamROI_line2);
            string downCircleFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calibup") + "//circle.hobj";
            if (File.Exists(downCircleFile)) downCamROI_circle.ReadObject(downCircleFile);           //读取roi
            else
            {
                MessageBox.Show("下相机circleRegion为空！");
                return false;
            }
            string downLine1File = Path.Combine(System.Environment.CurrentDirectory, "region", "calibup") + "//line1.hobj";
            if (File.Exists(downLine1File)) downCamROI_line1.ReadObject(downLine1File);           //读取roi
            else
            {
                MessageBox.Show("下相机line1Region为空！");
                return false;
            }
            string downLine2File = Path.Combine(System.Environment.CurrentDirectory, "region", "calibup") + "//line2.hobj";
            if (File.Exists(downLine2File)) downCamROI_line2.ReadObject(downLine2File);           //读取roi
            else
            {
                MessageBox.Show("下相机line2Region为空！");
                return false;
            }
            if (!halconAlgorithm.GetSpringPosition_match(ho_Image, hv_matchModel, ProjectInfo.Parameter.calibUpMatchPara, ProjectInfo.Parameter.calibUpFitCirclePara,
                ProjectInfo.Parameter.calibUpFitLine1Para, ProjectInfo.Parameter.calibUpFitLine2Para, downCamROI_circle, downCamROI_line1, downCamROI_line2, ProjectInfo.Parameter.calibUpOutCircleRadius ,
                ProjectInfo.Parameter.calibUpSeekCornerStartPhi, ProjectInfo.Parameter.calibUpSeekCornerEndPhi,
                out ho_fitCircleContour, out ho_fitLine1Contour, out ho_fitLine2Contour,
                out ho_fitAngleLine, out circle_X, out circle_Y, out angle, out bugInfo))
            {
                MessageBox.Show(bugInfo);
                return false;
            }
            if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 0)   //基于形状
            {
                HOperatorSet.ClearShapeModel(hv_matchModel);                     //清除模板
            }
            else if (ProjectInfo.Parameter.calibMatchPara.modelMatchType == 1)  //基于灰度
            {
                HOperatorSet.ClearNccModel(hv_matchModel);                   //清除模板
            }
            return true;
        }
        private void ho_AdaptiveImage(HWindowControl hv_showImageControl, int hv_ImageWidth, int hv_ImageHeight)
        {
            double rWindow = hv_showImageControl.Width * 1.0f / hv_showImageControl.Height;
            double rImage = hv_ImageWidth * 1.0f / hv_ImageHeight;
            if (rWindow > rImage)
            {
                double nw = (hv_ImageWidth * rWindow / rImage - hv_ImageWidth) / 2;
                double showWidth = nw + hv_ImageWidth;
                HOperatorSet.SetPart(hv_showImageControl.HalconWindow, 0, nw * (-1), hv_ImageHeight, showWidth);
            }
            else
            {
                double nh = (hv_showImageControl.Height - hv_showImageControl.Width / rImage) * hv_ImageHeight / hv_showImageControl.Height;
                double showHeight = nh + hv_ImageHeight;
                HOperatorSet.SetPart(hv_showImageControl.HalconWindow, nh * (-1), 0, showHeight, hv_ImageWidth);
            }
        }
        private void btn_getRotate1Pos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(6);
        }

        private void btn_getUpPos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(2);
        }

        private void btn_getRotate2Pos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(7);
        }

        private void btn_getLeftPos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(4);
        }

        private void btn_getCenterPos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(1);
        }

        private void btn_getRightPos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(5);
        }

        private void btn_getDownPos_Click(object sender, EventArgs e)
        {
            GetAloneCalibImage(3);
        }
        private void GetAloneCalibImage(int curCalibIndex)
        {
            if (this.cB_getImageType.SelectedIndex == 0)
            {
                //在线
                photoSignal = true;
                curOffCalibIndex = curCalibIndex;
            }
            else if (this.cB_getImageType.SelectedIndex == 1)
            {
                //离线读图
                curOffCalibIndex = curCalibIndex;
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "图片文件(*.jpg,*.tif,*.bmp,*.Png)|*.jpg;*.tif;*.bmp;*.Png";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Bitmap image = new Bitmap(new MemoryStream(File.ReadAllBytes(openFileDialog.FileName)));
                    //Bitmap image = new Bitmap(openFileDialog.FileName);
                    if (aloneCalibQueue.IsEmpty)        //防止队列积累内存
                        aloneCalibQueue.Enqueue(image);
                }
            }
        }
        private void btn_GetDownCamPixSize_Click(object sender, EventArgs e)
        {
            if (this.lab_curRotate1Pos.BackColor == Color.Green && this.lab_curRotate2Pos.BackColor == Color.Green && this.lab_curCenterPos.BackColor == Color.Green && this.lab_curUpPos.BackColor == Color.Green
                && this.lab_curDownPos.BackColor == Color.Green && this.lab_curLeftPos.BackColor == Color.Green && this.lab_curRightPos.BackColor == Color.Green)
            {
                try
                {
                    double pixSize_X = (double.Parse(this.tB_moveStep_X.Text) / Math.Abs(curPixelPos_X[4] - curPixelPos_X[0]) + double.Parse(this.tB_moveStep_X.Text) / Math.Abs(curPixelPos_X[3] - curPixelPos_X[0])) / 2;
                    //double pixSize_X = (curPixelPos_X[4] - curPixelPos_X[3]) / 2 * double.Parse(this.tB_moveStep_X.Text);      //x轴方向的像素当量                               
                    //double pixSize_Y = (curPixelPos_Y[2] - curPixelPos_Y[1]) / 2 * double.Parse(this.tB_moveStep_Y.Text);      //y轴方向的像素当量                               
                    double pixSize_Y = (double.Parse(this.tB_moveStep_Y.Text) / Math.Abs(curPixelPos_Y[2] - curPixelPos_Y[0]) + double.Parse(this.tB_moveStep_Y.Text) / Math.Abs(curPixelPos_Y[1] - curPixelPos_Y[0])) / 2;
                    double pixSize_Phi = ((double.Parse(this.tB_rotateStep.Text) * Math.PI / 180) / Math.Abs(curPixelAngle[5] - curPixelAngle[0]) + (double.Parse(this.tB_rotateStep.Text) * Math.PI / 180) / Math.Abs(curPixelAngle[6] - curPixelAngle[0])) / 2;

                    //double pixSize_Phi = (curPixelAngle[5] - curPixelAngle[6]) / 2 * double.Parse(this.tB_rotateStep.Text);   //旋转角度的像素当量，方向待验证                              
                    this.tB_downCampixelSize_X.Text = pixSize_X.ToString();
                    this.tB_downCampixelSize_Y.Text = pixSize_Y.ToString();
                    this.tB_downCampixelSize_Phi.Text = pixSize_Phi.ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("检测到标定数据未完成");
                return;
            }
        }

        private void btn_GetUpCamPixSize_Click(object sender, EventArgs e)
        {
            if (this.lab_curCenterPos.BackColor == Color.Green && this.lab_curUpPos.BackColor == Color.Green && this.lab_curDownPos.BackColor == Color.Green)
            {
                try
                {
                    double pixSize_Y = (double.Parse(this.tB_moveStep_Y.Text) / Math.Abs(curPixelPos_X[2] - curPixelPos_X[0]) + double.Parse(this.tB_moveStep_Y.Text) / Math.Abs(curPixelPos_X[1] - curPixelPos_X[0])) / 2;
                    //double pixSize_Y = (curPixelPos_Y[2] - curPixelPos_Y[1]) / 2 * double.Parse(this.tB_moveStep_Y.Text);   //y轴方向的像素当量                           
                    this.tB_upCampixelSize_Y.Text = pixSize_Y.ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("检测到标定数据未完成");
                return;
            }
        }

        private void cB_selCalCamera_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.cB_selCalCamera.SelectedIndex)
            {
                case 0:
                    //下相机标定七步
                    this.tableLayoutPanel6.Visible = true;
                    this.tableLayoutPanel10.Visible = true;
                    this.tableLayoutPanel12.Visible = true;
                    this.tableLayoutPanel16.Visible = true;
                    calibModel = CalibModel.七步;
                    calibTotalNum = 7;
                    curPixelPos_X = new double[7];                             //初始化坐标数组
                    curPixelPos_Y = new double[7];
                    curPixelAngle = new double[7];                             //初始化角度数组
                    break;
                case 1:
                    //上相机标定三步
                    this.tableLayoutPanel6.Visible = false;
                    this.tableLayoutPanel10.Visible = false;
                    this.tableLayoutPanel12.Visible = false;
                    this.tableLayoutPanel16.Visible = false;
                    calibModel = CalibModel.三步;
                    calibTotalNum = 3;
                    curPixelPos_Y = new double[3];
                    break;
            }
        }

        private void btn_getDownImgFromFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件(*.jpg,*.tif,*.bmp,*.Png)|*.jpg;*.tif;*.bmp;*.Png";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                HObject ho_Image = null;
                HOperatorSet.GenEmptyObj(out ho_Image);
                ho_Image.Dispose();
                HOperatorSet.ReadImage(out ho_Image, openFileDialog.FileName);    //加载图像
                HTuple hv_ImageWidth, hv_ImageHeight;
                HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
                ho_AdaptiveImage(hWindow_reDownCam, hv_ImageWidth, hv_ImageHeight);
                hWindow_reDownCam.HalconWindow.ClearWindow();
                HOperatorSet.DispObj(ho_Image, hWindow_reDownCam.HalconWindow);
                //后续可以增加走位时的处理
                double circle_X = 0;
                double circle_Y = 0;
                double angle = 0;
                HObject ho_fitCircleContour = null;
                HObject ho_fitLine1Contour = null;
                HObject ho_fitLine2Contour = null;
                HObject ho_fitAngleLine = null;
                if (ProcessDownCamImage(ho_Image, out ho_fitCircleContour, out ho_fitLine1Contour, out circle_X, out circle_Y, out angle))
                {
                    HOperatorSet.DispObj(ho_fitCircleContour, hWindow_reDownCam.HalconWindow);
                    HOperatorSet.DispObj(ho_fitLine1Contour, hWindow_reDownCam.HalconWindow);
                    HOperatorSet.DispObj(ho_fitLine2Contour, hWindow_reDownCam.HalconWindow);
                    HOperatorSet.DispObj(ho_fitAngleLine, hWindow_reDownCam.HalconWindow);
                    this.Invoke(new Action(() =>
                    {
                        this.tB_dCamStandPos_X.Text = circle_X.ToString("f3");
                        this.tB_dCamStandPos_Y.Text = circle_Y.ToString("f3");
                        this.tB_dCamStandPos_Phi.Text = angle.ToString("f3");
                    }));
                }
                ho_fitCircleContour.Dispose();
                ho_fitLine1Contour.Dispose();
                ho_fitLine2Contour.Dispose();
                ho_fitAngleLine.Dispose();
            }
        }

        private void btn_getUpImgFromFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件(*.jpg,*.tif,*.bmp,*.Png)|*.jpg;*.tif;*.bmp;*.Png";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                HObject ho_Image = null;
                HOperatorSet.GenEmptyObj(out ho_Image);
                ho_Image.Dispose();
                HOperatorSet.ReadImage(out ho_Image, openFileDialog.FileName);    //加载图像
                HTuple hv_ImageWidth, hv_ImageHeight;
                HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
                ho_AdaptiveImage(hWindow_reUpCam, hv_ImageWidth, hv_ImageHeight);
                hWindow_reUpCam.HalconWindow.ClearWindow();
                HOperatorSet.DispObj(ho_Image, hWindow_reUpCam.HalconWindow);
                //后续可以增加走位时的处理
                double circle_X = 0;
                double circle_Y = 0;
                double angle = 0;
                HObject ho_fitCircleContour = null;
                HObject ho_fitLine1Contour = null;
                HObject ho_fitLine2Contour = null;
                HObject ho_fitAngleLine = null;
                if (ProcessUpCamImage(ho_Image, out ho_fitCircleContour, out ho_fitLine1Contour, out ho_fitLine2Contour, out ho_fitAngleLine, out circle_X, out circle_Y, out angle))
                {
                    HOperatorSet.DispObj(ho_fitCircleContour, hWindow_reUpCam.HalconWindow);
                    HOperatorSet.DispObj(ho_fitLine1Contour, hWindow_reUpCam.HalconWindow);
                    HOperatorSet.DispObj(ho_fitLine2Contour, hWindow_reUpCam.HalconWindow);
                    HOperatorSet.DispObj(ho_fitAngleLine, hWindow_reUpCam.HalconWindow);
                    this.Invoke(new Action(() =>
                    {
                        this.tB_uCamStandPos_X.Text = circle_X.ToString("f3");
                        this.tB_uCamStandPos_Y.Text = circle_Y.ToString("f3");
                        this.tB_uCamStandPos_Phi.Text = angle.ToString("f3");
                    }));
                }
                ho_fitCircleContour.Dispose();
                ho_fitLine1Contour.Dispose();
                ho_fitLine2Contour.Dispose();
                ho_fitAngleLine.Dispose();
            }
        }

        private void btn_closeFom_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ShareData.cameralOpenList.Count; i++)
            {
                ShareData.MvsCameral.StopHKCamGrab(i);    //停止采集
                ShareData.MvsCameral.DestroyHKCam(i);   //关闭设备
            }
            ShareData.MvsCameral.captureImage -= MvsCameral_captureImage;              //松绑
            this.Close();
        }

        private void btn_savePara_Click(object sender, EventArgs e)
        {
            try
            {
                ShareData.downCamPixSize_X = double.Parse(this.tB_downCampixelSize_X.Text);
                ShareData.downCamPixSize_Y = double.Parse(this.tB_downCampixelSize_Y.Text);
                ShareData.downCamPixSize_Phi = double.Parse(this.tB_downCampixelSize_Phi.Text);
                ShareData.upCamPixSize1_Y = double.Parse(this.tB_upCampixelSize_Y.Text);

                ShareData.calParaIni.WriteIniData("camCalib", "dcam_X", ShareData.downCamPixSize_X.ToString());
                ShareData.calParaIni.WriteIniData("camCalib", "dcam_Y", ShareData.downCamPixSize_Y.ToString());
                ShareData.calParaIni.WriteIniData("camCalib", "dcam_Phi", ShareData.downCamPixSize_Phi.ToString());
                ShareData.calParaIni.WriteIniData("camCalib", "ucam_Y", ShareData.upCamPixSize1_Y.ToString());

                ShareData.dowCamStandPos_X = double.Parse(this.tB_dCamStandPos_X.Text);
                ShareData.dowCamStandPos_Y = double.Parse(this.tB_dCamStandPos_Y.Text);
                ShareData.dowCamStandPos_Phi = double.Parse(this.tB_dCamStandPos_Phi.Text);

                ShareData.upCamStandPos1_X = double.Parse(this.tB_uCamStandPos_X.Text);
                ShareData.upCamStandPos1_Y = double.Parse(this.tB_uCamStandPos_Y.Text);
                ShareData.upCamStandPos1_Phi = double.Parse(this.tB_uCamStandPos_Phi.Text);

                ShareData.calParaIni.WriteIniData("spos", "dcam_X", ShareData.dowCamStandPos_X.ToString());
                ShareData.calParaIni.WriteIniData("spos", "dcam_Y", ShareData.dowCamStandPos_Y.ToString());
                ShareData.calParaIni.WriteIniData("spos", "dcam_Phi", ShareData.dowCamStandPos_Phi.ToString());
                ShareData.calParaIni.WriteIniData("spos", "dup_X", ShareData.upCamStandPos1_X.ToString());
                ShareData.calParaIni.WriteIniData("spos", "dup_Y", ShareData.upCamStandPos1_Y.ToString());
                ShareData.calParaIni.WriteIniData("spos", "dup_Phi", ShareData.upCamStandPos1_Phi.ToString());

                ProjectInfo.Parameter.calibOutCircleRadius = double.Parse(this.tB_calibOutCircleRadius.Text);
                ProjectInfo.Parameter.calibSeekCornerStartPhi = double.Parse(this.tB_calibSeekStartPhi.Text);
                ProjectInfo.Parameter.calibSeekCornerEndPhi = double.Parse(this.tB_calibSeekEndPhi.Text);

                ProjectInfo.Parameter.calibUpOutCircleRadius = double.Parse(this.tB_calibUpOutCircleRadius.Text);
                ProjectInfo.Parameter.calibUpSeekCornerStartPhi = double.Parse(this.tB_calibUpSeekStartPhi.Text);
                ProjectInfo.Parameter.calibUpSeekCornerEndPhi = double.Parse(this.tB_calibUpSeekEndPhi.Text);

                ProjectInfo.SaveParameter(ShareData.configPath); //保存配置文件 
                MessageBox.Show("保存参数成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存参数失败！");
            }
        }

        private void btn_getDownCamStandPos_Click(object sender, EventArgs e)
        {
            getDownCamStandPos = true;
        }

        private void btn_getUpCamStandPos_Click(object sender, EventArgs e)
        {
            getUpCamStandPos = true;
        }
        #region 标定算法
        private void btn_calibMatch_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibMatchPara == null) ProjectInfo.Parameter.calibMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calib");
            MatchForm matchForm = new MatchForm(ProjectInfo.Parameter.calibMatchPara, modelImageFold);
            matchForm.ShowDialog();
            ProjectInfo.Parameter.calibMatchPara.modelLocationCol = matchForm.outMatchPara.modelLocationCol;
            ProjectInfo.Parameter.calibMatchPara.modelLocationRow = matchForm.outMatchPara.modelLocationRow;
            ProjectInfo.Parameter.calibMatchPara.modelMatchType = matchForm.outMatchPara.modelMatchType;
            ProjectInfo.Parameter.calibMatchPara.seekAngleRange = matchForm.outMatchPara.seekAngleRange;
            ProjectInfo.Parameter.calibMatchPara.seekAngleStart = matchForm.outMatchPara.seekAngleStart;
            ProjectInfo.Parameter.calibMatchPara.seekModelNum = matchForm.outMatchPara.seekModelNum;
            ProjectInfo.Parameter.calibMatchPara.seekModelScore = matchForm.outMatchPara.seekModelScore;
        }

        private void btn_calibFitCircle_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibFitCirclePara == null) ProjectInfo.Parameter.calibFitCirclePara = new FitCirclePara();
            if (ProjectInfo.Parameter.calibMatchPara == null) ProjectInfo.Parameter.calibMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calib");
            HObject hv_region = null;
            HOperatorSet.GenEmptyObj(out hv_region);
            string regionFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calib") + "//circle.hobj";
            if (File.Exists(regionFile)) hv_region.ReadObject(regionFile);           //读取roi
            FitCircleForm fitCircleForm = new FitCircleForm(ProjectInfo.Parameter.calibFitCirclePara, hv_region);
            fitCircleForm.LoadMatchPara(modelImageFold, ProjectInfo.Parameter.calibMatchPara);
            fitCircleForm.ShowDialog();
            fitCircleForm.hv_saveRegion.WriteObject(regionFile);
            ProjectInfo.Parameter.calibFitCirclePara.contrast = fitCircleForm.outFitCirclePara.contrast;
            ProjectInfo.Parameter.calibFitCirclePara.fitNum = fitCircleForm.outFitCirclePara.fitNum;
            ProjectInfo.Parameter.calibFitCirclePara.maxGray = fitCircleForm.outFitCirclePara.maxGray;
            ProjectInfo.Parameter.calibFitCirclePara.minGray = fitCircleForm.outFitCirclePara.minGray;
            ProjectInfo.Parameter.calibFitCirclePara.seekPointPath = fitCircleForm.outFitCirclePara.seekPointPath;
            ProjectInfo.Parameter.calibFitCirclePara.sigma = fitCircleForm.outFitCirclePara.sigma;
            ProjectInfo.Parameter.calibFitCirclePara.isInheritModel = fitCircleForm.outFitCirclePara.isInheritModel;
            hv_region.Dispose();
        }

        private void btn_calibFitLine1_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibFitLine1Para == null) ProjectInfo.Parameter.calibFitLine1Para = new FitLinePara();
            if (ProjectInfo.Parameter.calibMatchPara == null) ProjectInfo.Parameter.calibMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calib");
            HObject hv_region = null;
            HOperatorSet.GenEmptyObj(out hv_region);
            string regionFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calib") + "//line1.hobj";
            if (File.Exists(regionFile)) hv_region.ReadObject(regionFile);           //读取roi
            FitLineForm fitLineForm = new FitLineForm(ProjectInfo.Parameter.calibFitLine1Para, hv_region);
            fitLineForm.LoadMatchPara(modelImageFold, ProjectInfo.Parameter.calibMatchPara);
            fitLineForm.ShowDialog();
            fitLineForm.hv_saveRegion.WriteObject(regionFile);
            ProjectInfo.Parameter.calibFitLine1Para.contrast = fitLineForm.outFitLinePara.contrast;
            ProjectInfo.Parameter.calibFitLine1Para.fitNum = fitLineForm.outFitLinePara.fitNum;
            ProjectInfo.Parameter.calibFitLine1Para.grayTransition = fitLineForm.outFitLinePara.grayTransition;
            ProjectInfo.Parameter.calibFitLine1Para.LSAngle = fitLineForm.outFitLinePara.LSAngle;
            ProjectInfo.Parameter.calibFitLine1Para.LSJudge = fitLineForm.outFitLinePara.LSJudge;
            ProjectInfo.Parameter.calibFitLine1Para.pointPosition = fitLineForm.outFitLinePara.pointPosition;
            ProjectInfo.Parameter.calibFitLine1Para.sigma = fitLineForm.outFitLinePara.sigma;
            ProjectInfo.Parameter.calibFitLine1Para.isInheritModel = fitLineForm.outFitLinePara.isInheritModel;
            hv_region.Dispose();
        }

        private void btn_calibFitLine2_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibFitLine2Para == null) ProjectInfo.Parameter.calibFitLine2Para = new FitLinePara();
            if (ProjectInfo.Parameter.calibMatchPara == null) ProjectInfo.Parameter.calibMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calib");
            HObject hv_region = null;
            HOperatorSet.GenEmptyObj(out hv_region);
            string regionFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calib") + "//line2.hobj";
            if (File.Exists(regionFile)) hv_region.ReadObject(regionFile);           //读取roi
            FitLineForm fitLineForm = new FitLineForm(ProjectInfo.Parameter.calibFitLine2Para, hv_region);
            fitLineForm.LoadMatchPara(modelImageFold, ProjectInfo.Parameter.calibMatchPara);      //加载匹配参数
            fitLineForm.ShowDialog();
            fitLineForm.hv_saveRegion.WriteObject(regionFile);                      //写入roi
            ProjectInfo.Parameter.calibFitLine2Para.contrast = fitLineForm.outFitLinePara.contrast;
            ProjectInfo.Parameter.calibFitLine2Para.fitNum = fitLineForm.outFitLinePara.fitNum;
            ProjectInfo.Parameter.calibFitLine2Para.grayTransition = fitLineForm.outFitLinePara.grayTransition;
            ProjectInfo.Parameter.calibFitLine2Para.LSAngle = fitLineForm.outFitLinePara.LSAngle;
            ProjectInfo.Parameter.calibFitLine2Para.LSJudge = fitLineForm.outFitLinePara.LSJudge;
            ProjectInfo.Parameter.calibFitLine2Para.pointPosition = fitLineForm.outFitLinePara.pointPosition;
            ProjectInfo.Parameter.calibFitLine2Para.sigma = fitLineForm.outFitLinePara.sigma;
            ProjectInfo.Parameter.calibFitLine2Para.isInheritModel = fitLineForm.outFitLinePara.isInheritModel;
            hv_region.Dispose();
        }
        #endregion

        private void btn_calibUpMatch_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibUpMatchPara == null) ProjectInfo.Parameter.calibUpMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calibup");
            MatchForm matchForm = new MatchForm(ProjectInfo.Parameter.calibUpMatchPara, modelImageFold);
            matchForm.ShowDialog();
            ProjectInfo.Parameter.calibUpMatchPara.modelLocationCol = matchForm.outMatchPara.modelLocationCol;
            ProjectInfo.Parameter.calibUpMatchPara.modelLocationRow = matchForm.outMatchPara.modelLocationRow;
            ProjectInfo.Parameter.calibUpMatchPara.modelMatchType = matchForm.outMatchPara.modelMatchType;
            ProjectInfo.Parameter.calibUpMatchPara.seekAngleRange = matchForm.outMatchPara.seekAngleRange;
            ProjectInfo.Parameter.calibUpMatchPara.seekAngleStart = matchForm.outMatchPara.seekAngleStart;
            ProjectInfo.Parameter.calibUpMatchPara.seekModelNum = matchForm.outMatchPara.seekModelNum;
            ProjectInfo.Parameter.calibUpMatchPara.seekModelScore = matchForm.outMatchPara.seekModelScore;
        }

        private void btn_calibUpFitCircle_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibUpFitCirclePara == null) ProjectInfo.Parameter.calibUpFitCirclePara = new FitCirclePara();
            if (ProjectInfo.Parameter.calibUpMatchPara == null) ProjectInfo.Parameter.calibUpMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calibup");
            HObject hv_region = null;
            HOperatorSet.GenEmptyObj(out hv_region);
            string regionFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calibup") + "//circle.hobj";
            if (File.Exists(regionFile)) hv_region.ReadObject(regionFile);           //读取roi
            FitCircleForm fitCircleForm = new FitCircleForm(ProjectInfo.Parameter.calibUpFitCirclePara, hv_region);
            fitCircleForm.LoadMatchPara(modelImageFold, ProjectInfo.Parameter.calibUpMatchPara);
            fitCircleForm.ShowDialog();
            fitCircleForm.hv_saveRegion.WriteObject(regionFile);
            ProjectInfo.Parameter.calibUpFitCirclePara.contrast = fitCircleForm.outFitCirclePara.contrast;
            ProjectInfo.Parameter.calibUpFitCirclePara.fitNum = fitCircleForm.outFitCirclePara.fitNum;
            ProjectInfo.Parameter.calibUpFitCirclePara.maxGray = fitCircleForm.outFitCirclePara.maxGray;
            ProjectInfo.Parameter.calibUpFitCirclePara.minGray = fitCircleForm.outFitCirclePara.minGray;
            ProjectInfo.Parameter.calibUpFitCirclePara.seekPointPath = fitCircleForm.outFitCirclePara.seekPointPath;
            ProjectInfo.Parameter.calibUpFitCirclePara.sigma = fitCircleForm.outFitCirclePara.sigma;
            ProjectInfo.Parameter.calibUpFitCirclePara.isInheritModel = fitCircleForm.outFitCirclePara.isInheritModel;
            hv_region.Dispose();
        }

        private void btn_calibUpFitLine1_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibUpFitLine1Para == null) ProjectInfo.Parameter.calibUpFitLine1Para = new FitLinePara();
            if (ProjectInfo.Parameter.calibUpMatchPara == null) ProjectInfo.Parameter.calibUpMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calibup");
            HObject hv_region = null;
            HOperatorSet.GenEmptyObj(out hv_region);
            string regionFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calibup") + "//line1.hobj";
            if (File.Exists(regionFile)) hv_region.ReadObject(regionFile);           //读取roi
            FitLineForm fitLineForm = new FitLineForm(ProjectInfo.Parameter.calibUpFitLine1Para, hv_region);
            fitLineForm.LoadMatchPara(modelImageFold, ProjectInfo.Parameter.calibUpMatchPara);
            fitLineForm.ShowDialog();
            fitLineForm.hv_saveRegion.WriteObject(regionFile);
            ProjectInfo.Parameter.calibUpFitLine1Para.contrast = fitLineForm.outFitLinePara.contrast;
            ProjectInfo.Parameter.calibUpFitLine1Para.fitNum = fitLineForm.outFitLinePara.fitNum;
            ProjectInfo.Parameter.calibUpFitLine1Para.grayTransition = fitLineForm.outFitLinePara.grayTransition;
            ProjectInfo.Parameter.calibUpFitLine1Para.LSAngle = fitLineForm.outFitLinePara.LSAngle;
            ProjectInfo.Parameter.calibUpFitLine1Para.LSJudge = fitLineForm.outFitLinePara.LSJudge;
            ProjectInfo.Parameter.calibUpFitLine1Para.pointPosition = fitLineForm.outFitLinePara.pointPosition;
            ProjectInfo.Parameter.calibUpFitLine1Para.sigma = fitLineForm.outFitLinePara.sigma;
            ProjectInfo.Parameter.calibUpFitLine1Para.isInheritModel = fitLineForm.outFitLinePara.isInheritModel;
            hv_region.Dispose();
        }

        private void btn_calibUpFitLine2_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.Parameter.calibUpFitLine2Para == null) ProjectInfo.Parameter.calibUpFitLine2Para = new FitLinePara();
            if (ProjectInfo.Parameter.calibUpMatchPara == null) ProjectInfo.Parameter.calibUpMatchPara = new MatchPara();
            string modelImageFold = Path.Combine(System.Environment.CurrentDirectory, "model", "calibup");
            HObject hv_region = null;
            HOperatorSet.GenEmptyObj(out hv_region);
            string regionFile = Path.Combine(System.Environment.CurrentDirectory, "region", "calibup") + "//line2.hobj";
            if (File.Exists(regionFile)) hv_region.ReadObject(regionFile);           //读取roi
            FitLineForm fitLineForm = new FitLineForm(ProjectInfo.Parameter.calibUpFitLine2Para, hv_region);
            fitLineForm.LoadMatchPara(modelImageFold, ProjectInfo.Parameter.calibUpMatchPara);      //加载匹配参数
            fitLineForm.ShowDialog();
            fitLineForm.hv_saveRegion.WriteObject(regionFile);                      //写入roi
            ProjectInfo.Parameter.calibUpFitLine2Para.contrast = fitLineForm.outFitLinePara.contrast;
            ProjectInfo.Parameter.calibUpFitLine2Para.fitNum = fitLineForm.outFitLinePara.fitNum;
            ProjectInfo.Parameter.calibUpFitLine2Para.grayTransition = fitLineForm.outFitLinePara.grayTransition;
            ProjectInfo.Parameter.calibUpFitLine2Para.LSAngle = fitLineForm.outFitLinePara.LSAngle;
            ProjectInfo.Parameter.calibUpFitLine2Para.LSJudge = fitLineForm.outFitLinePara.LSJudge;
            ProjectInfo.Parameter.calibUpFitLine2Para.pointPosition = fitLineForm.outFitLinePara.pointPosition;
            ProjectInfo.Parameter.calibUpFitLine2Para.sigma = fitLineForm.outFitLinePara.sigma;
            ProjectInfo.Parameter.calibUpFitLine2Para.isInheritModel = fitLineForm.outFitLinePara.isInheritModel;
            hv_region.Dispose();
        }
    }
}
